flopt = flsys:NewModule("flopt", "AceConsole-3.0", "AceEvent-3.0")

function flopt:OnEnable()
	self.db = LibStub("AceDB-3.0"):New("FlamingLootSysDB")
	local db = self.db.profile
	local options = {
		name = "|cff6600FFflaming loot ml|r",
		handler = flopt,
		type = "group",
		hidden=false,
		childGroups="tab",
		args = {
			Amode = {
				name = "Mode",
				type = "group",
				order=01,
				cmdHidden = true,
				args = {
					Mode = {
						type = "select",
						order = 2,
						values = {
							[1]="Default",
							[2.1]="Single, GP",
							[2.2]="Single, count",
						},
						name = "Addon mode",
						confirm = true,
						confirmText = "Change the addon mode? Changing to a single mode will erase all your stored data.",
						get = function(info) return flsys.db.profile.mode end,
						set = function(info, input)
							if flsys.db.profile.inprogress then
								StaticPopup_Show("NOTDURINGRAID")
							elseif input~=flsys.db.profile.mode then
								flsys.db.profile.mode = input
								ModeDisplay(input, true)
							end
						end,	
					},
					ModeWarning = {
					type="description",
						width="full",
						order=1,
						name = "\n|cffFFD100WARNING:|r Switching to either of the current raid only modes will reset all of your stored player data.\n",
					},
					DESCMode = {
						type="description",
						width="full",
						order=3,
						name = "\nDefault: Tracks ep and gear received over multiple raids and determines loot priority accordingly.\n\nSingle: Tracks the current raid only, resetting after each raid.\n\n  -GP: Uses normal GP values for mainspec rolls, which takes slot and user into account.\n\n  -Count: Uses a simple count, so all items have equal value."
					},
				},
			},
			System = {
				name = "System",
				handler = flsys,
				type = "group",
				order=02,
				cmdHidden = true,
				args = {
					HEADERSettings = {
						order=0,
						type = "header",
						name = "Settings",
					},
					RaidstoCount = {
						order=3,
						type = "input",
						pattern = "%d+",
						name = "Number of raids",
						--width="half",
						desc = "How long a raid should be factored into player data", --FIX better description
						get = function(info) 
							return tostring(db.raidstocount)
							end,
						set = function(info, input) 
							if db.inprogress then
								StaticPopup_Show("NOTDURINGRAID")
							else
								if tonumber(dialog.input)>1 and tonumber(dialog.input)<30 then
									local dialog = StaticPopup_Show("CONFIRM_RAIDSTOCOUNT")
									if dialog then
										dialog.input = tonumber(input)
									end
								else
									flsys:Print("Please enter a number between 2 and 30.  If you only want to count the current raid, change the addon mode.")
								end
							end
							end,
					},
					MinGP = {
						order=6,
						name = "Minimum GP", 
						type = "input",
						pattern = "%d+",
						--width="half",
						cmdHidden = true,
						desc = "Used to calculate PR for players that have no GP or fall below the min GP",
						set = function(info, input)
							flsys.db.profile.min_gp=tonumber(input)
							flsys:GetConstants()
							end,
						get = function(info)
							return tostring(flsys.db.profile.min_gp)
							end,
					},
					iLvl = {
						order=10,
						name = "Standard ilvl", 
						type = "select",
						values = {
						[378] = 378,
						[391] = 391,
						[397] = 397,
						[410] = 410,
						},
						cmdHidden = true,
						desc = "NOTE: Changing this will scale all current GP accordingly.",
						set = function(info, input)
							local dialog = StaticPopup_Show("STANDARDILVL", input)
							if dialog then
								dialog.old = flsys.db.profile.standard_ilvl
								dialog.new = input
							end
						end,
						get = function(info)
							return flsys.db.profile.standard_ilvl
							end,
					},
					RecurAmt = {
						order=11,
						name = "Recurring amt", 
						type = "input",
						pattern = "%d+",
						cmdHidden = true,
						--width="half",
						desc = "Set the EP amount for recurring mass awards",
						set = function(info, input)
							flsys.db.profile.ep_amt=tonumber(input)
							flsys:GetConstants()
							end,
						get = function(info)
							return tostring(db.ep_amt)
							end,
					},
					RecurTime = {
						order=12,
						name = "Recurring time", 
						type = "input",
						pattern = "%d+",
						--width="half",
						cmdHidden = true,
						desc = "How often recurring EP awards should take place (min)",
						set = function(info, input)
							flsys.db.profile.ep_recur=tonumber(input)
							flsys:GetConstants()
							end,
						get = function(info)
							return tostring(flsys.db.profile.ep_recur)
							end,
					},
					promptrecur = {
						name = "Prompt at start",
						order = 13,
						desc = "Prompt to start a recurring award when starting a raid?",
						type = "toggle",
						set = function(info,val) flsys.db.profile.promptrecur = val end,
						get = function(info) return flsys.db.profile.promptrecur end
					},
					zHEADERPLAYERS = {
						type = "header",
						name = "Players",
						order=14,
					},
					PlayerExplain = {
						type="description",
						width="full",
						name = "\nIMPORTANT: Check 'New' for players that are new to the team compared to others.  Their EP will be scaled appropriately - see the website for more info.\n",
						order=15,
					},
					Add= {
						name = "Add a player",
						type="execute",
						cmdHidden = true,
						desc="Add a player to the system",
						func = function() Import() end,
						order=16,
					},
					Remove= {
						name = "Remove a player",
						type="execute",
						handler = flopt,
						cmdHidden = true,
						desc="Remove a player from the system",
						func = function() 
							if db.inprogress then
								StaticPopup_Show("NOTDURINGRAID")
							else
								InterfaceOptionsFrame:Hide()
								FLRosterFrame:Show()
							end
							end,
						order=17,
					},
					Spacer18 = {
						type="description",
						width="normal",
						name = "\n",
						order=17,
					},
					AddAlt = {
						name = "Add or remove an alt", 
						type = "input",
						handler = flsys,
						pattern = "-?%a+=?%a*",
						order=18,
						cmdHidden = true,
						desc = "Altname=Playername.  Case sensitive!  Enter just the alt's name to remove it from the list.",
						set = "AddAlt",
					},
					Spacer57 = {
						type="description",
						width="full",
						name = "\n",
						order=22,
					},
					AltDisplay = {
						type="description",
						width="normal",
						name = function(info) return flsys:GetAlts() end,
						order=20,
					},
					HEADERDatabase = {
						type = "header",
						name = "Database",
						order=25,
					},
					
					Importt = {
						name = "Import data",
						type="execute",
						desc="Import EP, GP and expense balances",
						handler= flsys,
						cmdHidden = true,
						func = function()
							if db.inprogress then
								StaticPopup_Show("NOTDURINGRAID")
							else
								flsys:Import()
							end
						end,
						order=26,
					},
					Spacer3 = {
						type="description",
						width="normal",
						name = "\n\n\n\n",
						order=27,
					},
					Send = {
						name = "Send data",
						type="execute",
						handler= flsys,
						desc="Send all EP, GP and expense balances to another player",
						cmdHidden = true,
						func = function()
							InterfaceOptionsFrame:Hide()
							StaticPopup_Show("SENDDATA")
						end,
						order=28,
					},
					ResetLog = {
						name = "Reset expenses",
						type="execute",
						cmdHidden = true,
						func = "ResetExpenses",
						order=29,
					},
					ResetData = {
						name = "Reset all data",
						type="execute",
						cmdHidden = true,
						desc="Reset EP, GP and expense balance for all players",
						func = function(self)
							if db.inprogress then
								StaticPopup_Show("NOTDURINGRAID")
							else
								flsys:ResetDataPressed()
							end
						end,
						order=30,
					},	
					ResetGP = {
						name = "Reset GP",
						type = "execute",
						cmdHidden = true,
						desc="Reset all players' GP to 0.  Generally used at the start of an expansion.",
						func = function(self)
							if db.inprogress then
								StaticPopup_Show("NOTDURINGRAID")
							else
								flsys:ResetGPPressed()
							end
						end,
						order = 31,
					},
				},
			},
			Distribution = {
				name = "Distribution",
				handler = fld,
				type = "group",
				order = 05,
				cmdHidden = true,
				childGroups="tab",
				args = {	
					RarityThreshold = {
						type = "select",
						order = 2,
						values = {
							[2]="|cFF1eff00Uncommon|r",
							[3]="|cFF0070ddRare|r",
							[4]="|cFFa335eeEpic|r",
						},
						name = "Rarity threshold",
						desc = "The minimum item quality required to trigger the distribution module.",
						get = function(info) return fld.db.profile.rarity_threshold end,
						set = function(info, input) fld.db.profile.rarity_threshold = input end,
					},
					Spacer897 = {
						type="description",
						width="full",
						name = "\n",
						order=3,
					},
					Sharder = {
						type = "input",
						order = 4,
						cmdHidden = true,
						pattern="^%a+$",
						name = "Disenchanter",
						get = function(info) return fld.db.profile.sharder end,
						set = function(info, input) fld.db.profile.sharder = flsys:Cap(input) end,
					},	
					Seller = {
						type = "input",
						order = 6,
						cmdHidden = true,
						pattern="^%a+$",
						name = "Seller for need/pass items",
						get = function(info) return fld.db.profile.seller end,
						set = function(info, input) fld.db.profile.seller = flsys:Cap(input) end,
					},
					promptz = {
						name = "Prompt at start",
						desc = "Prompt to enter seller and sharder if there is no one in the raid assigned to those roles?",
						type = "toggle",
						order =7,
						set = function(info,val) fld.db.profile.promptz = val end,
						get = function(info) return fld.db.profile.promptz end
					},
					HEADERlists = {
						type="header",
						order=10,
						name="Roll options",
					},
					DESCRolloptsEp = {
						type="description",
						order = 12,
						name = "\nNeed - Mainspec upgrade.  Winner determined by pr.  Awards gp.\nSidegrade - Optional mainspec roll for items with the same or lower ilvl as current piece.  Winner determined by random roll, no gp.\nOffspec - Winner determined by random roll, no gp.\nGreed - Random roll option when MS/OS does not apply.  No gp award.\n"
					},
					Whisp = {
						name = "Print roll options",
						desc = "Include abbreviated roll options when announcing drops for people who don't have the addon and will be rolling through whispers.",
						type = "toggle",
						order =13,
						width="full",
						set = function(info,val) fld.db.profile.whispopts = val end,
						get = function(info) return fld.db.profile.whispopts end
					},		
					SidegradeOpt = {
						type = "select",
						order = 14,
						values = {
							["nsop"]="Yes",
							["nop"]="No",
						},
						name = "Sidegrade",
						desc = "Include sidegrade in between need and offspec? It is sorted by random roll and does not award GP",
						get = function(info) return fld.db.profile.defaultopts end,
						set = function(info, input) fld.db.profile.defaultopts = input end,	
					},
					BoeOpts = {
						type = "select",
						order = 16,
						values = {
							["false"]="Normal options",
							["np"]="Need/pass",
							["gp"]="Greed/pass",
						},
						name = "BoE items",
						desc = "Roll options for BoE items",
						get = function(info) return tostring(fld.db.profile.boeopts) end,
						set = function(info, input) 
						if input=="false" then
							fld.db.profile.boeopts = false
						else
							fld.db.profile.boeopts = input 
						end
						end,
					},
					EmberOpts = {
						type = "select",
						order = 17,
						values = {
							["false"]="Normal options",
							["np"]="Need/pass",
							["gp"]="Greed/pass",
						},
						name = "Crafting items",
						desc = "Roll options for Living Ember & Essence of Destruction",
						get = function(info) return tostring(fld.db.profile.emberopts) end,
						set = function(info, input) 
						if input=="false" then
							fld.db.profile.emberopts = false
						else
							fld.db.profile.emberopts = input 
						end
						end,
					},
					ItemNames = {
						type="description",
						order=19,
						width="full",
						name = "\n\nMake sure to spell & punctuate item names correctly.  They can be entered with their proper capitalization or in lower case.  Any names that have a capital letter partway through a word need to be entered that way."
					},
					AutoAssign = {
						type = "input",
						order=20,
						cmdHidden = true,
						name = "Auto-assign",
						pattern = "[%s%a]+=?%a*",
						desc = "Item Name=Player.  Proper case or lower case works - if there is mid-word capitalization make sure to enter that though.  Enter just the item name to remove it.",
						set = function(info, input)
							local item, player = string.match(input, "([%s%a]+)=?(%a*)")
							if item then
								item = flsys:Cap(item)
								if player=="" then
									flopt.db.profile.autoassign[item] = nil
								else
									player = flsys:Cap(player)
									flopt.db.profile.autoassign[item] = player
								end
							end
						end,
					},				
					AutoDisplay = {
						type="description",
						order=24,
						width="double",
						name = function(info) return fld:GetAutoAssign() end,
					},
				},			
			},
			Expenses = {
				name = "Raid Expenses",
				handler = flsys,
				type = "group",
				order=06,
				cmdHidden = true,
				args = {
					Feast = {
						order=1,
						name = "Feast", 
						type = "input",
						pattern = "%d+",
						cmdHidden = true,
						desc = "Cost of providing a feast",
						set = function(info, input)
							flsys.db.profile.costs.feast=tonumber(input)
							end,
						get = function(info)
							return tostring(flsys.db.profile.costs.feast)
							end,
					},
					Cauldron = {
						order=4,
						name = "Cauldron", 
						type = "input",
						pattern = "%d+",
						cmdHidden = true,
						desc = "Cost of providing a Cauldron of Battle",
						set = function(info, input)
							flsys.db.profile.costs.cauldron=tonumber(input)
							end,
						get = function(info)
							return tostring(flsys.db.profile.costs.cauldron)
							end,
					},
					Bcauldron = {
						order=8,
						name = "Big Cauldron", 
						type = "input",
						pattern = "%d+",
						cmdHidden = true,
						desc = "Cost of providing a Big Cauldron of Battle",
						set = function(info, input)
							flsys.db.profile.costs.bcauldron=tonumber(input)
							end,
						get = function(info)
							return tostring(flsys.db.profile.costs.bcauldron)
							end,
					},
					Auto = {
						name = "Automatic entry",
						order = 13,
						desc = "Automatically enter feast/cauldron drops and payments made via trade during raids.",
						type = "toggle",
						set = function(info,val) flsys.db.profile.autoexpense = val end,
						get = function(info) return flsys.db.profile.autoexpense end
					},
				},
			},		
			Help = {
				name = "Help",
				handler = flopt,
				order=08,
				type = "group",
				args = 	{
					Spacer0 = {
						type="description",
						width="full",
						name = " ",
						order=0,
					},
					HEADERMoreinfo = {
						type = "header",
						name = "More detailed information is available at |cff4444FFsites.google.com/site/flamingloot|r",
						order=1,
					},
					Spacer1 = {
						type="description",
						width="full",
						name = " ",
						order=2,
					},
					HEADERSetup = {
						type = "header",
						name = "Setup",
						order=6,
					},
					Setup = {
						type="description",
						width="full",
						name = "1. Select an addon mode in the system tab and look through all the settings.\n\nIf you are using the default ongoing mode:\n2. Add team members to your database using the 'Add Player' button in the system tab. This is important to do before using so that members aren't tagged as subs.\n3. It's highly recommended that you set up out-of-game data backup early on.  See the addon site for instructions.\n",
						order=9,
					},
					HEADERUse = {
						type = "header",
						name = "Use",
						order=12,
					},
					Use = {
						type="description",
						width="full",
						name = "Type /fss and hit Start when you are beginning a raid.\nEverything else is automatic except for features that you have changed to manual in your settings.\n",
						order=15,
					},
					HEADERSubs = {
						type = "header",
						name = "Subs (default mode only)",
						order=18,
					},
					Subs = {
						type="description",
						width="full",
						name = "Any player in your raid who is not in your database is considered a sub and will be removed from the system when the raid ends.  Subs have all the same rolling options as team members and have the same chance of winning a need roll as they would with an open roll.  If they don't win the roll, player priority is used to determine the winner as usual.  Subs who have won a mainspec item will only win a 2nd need roll if it is uncontested.\nPlayers can send you a tell saying 'sub' to get this information.\n",
						order=21,
					},
					HEADERWhisper = {
						type = "header",
						name = "Rolling via whisper",
						order=24,
					},
					Whisper = {
						type="description",
						width="full",
						name = "If a player does not have the flaming loot addon installed, they can roll via whisper instead.  Installing the addon is recommended since it is much faster and whisper rolls do not prevent rolling an item more than once or rolling on items the player cannot use.  You'll also need to end rolling manually since they won't be sending you pass rolls.\nFor instructions on how to roll, have the player send you a tell saying 'addon.'\n",
						order=27,
					},
					HEADERFeedback = {
						type = "header",
						name = "Errors, issues, questions",
						order=29,
					},
					Feedback = {
						type="description",
						width="full",
						name = "Visit sites.google.com/site/flamingloot/feedback",
						order=30,
					},
				}
			}
		},
	}
	
	function Import()
		InterfaceOptionsFrame:Hide()
		FLAddPlayer:Show()
	end

	function ModeDisplay(input, change)
		FLMain:Hide()
		if input==1 then
			options.args.System.hidden=false
			options.args.Expenses.hidden=false
			options.args.Distribution.args.DESCRolloptsEp.hidden=false
			options.args.Distribution.args.SidegradeOpt.hidden=false
			options.args.Amode.args.iLvl = nil
		else
			options.args.System.hidden=true
			options.args.Expenses.hidden=true
			options.args.Distribution.args.DESCRolloptsEp.hidden=true
			options.args.Distribution.args.SidegradeOpt.hidden=true
			flsys.db.profile.autoexpense = false
		end
		if input==2.1 then
			options.args.Amode.args.iLvl = options.args.System.args.iLvl
		end
		InterfaceOptionsFrame_OpenToCategory("Flaming Loot")
		if change then
			flsys:ModeChanged(input)
		end
	end
	LibStub("AceConfig-3.0"):RegisterOptionsTable("flopt", options, {"flopt"})
	flopt.optionsFrame = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("flopt", "flaming loot ml")
	ModeDisplay(flsys.db.profile.mode)
end

StaticPopupDialogs["STANDARDILVL"] = {
	text = "Change the standard ilvl to %s? This will rescale all GP.",
	button1 = "Yes",
	button2 = CANCEL,
	timeout = 0,
	enterClicksFirstButton = true,
	whileDead = 1,                  
	OnAccept = function(self) 
		flsys.db.profile.standard_ilvl = self.new
		flsys:ScaleGP(self.old, self.new)
		end,	
}